package com.yiboshi.rehrs.helper;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.github.benmanes.caffeine.cache.Cache;
import com.yiboshi.rehrs.common.ZhongConfig;
import com.yiboshi.rehrs.util.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpHost;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;

/**
 * @author jack 2025/3/16
 */
@Slf4j
@Component
public class ZhongConfigHelper {

    @Value("${zhong.config-file}")
    String configFilename;

    @Autowired
    RedisHelper redisHelper;

    Map<Integer, ZhongConfig> hashMap = new ConcurrentHashMap<>();
    JSONObject jsonObject = null;
    Map<String, String> fiddleHeader = null;

    public Map<String, String> fiddleMap() {
        getConfig(0);
        return new HashMap<>(fiddleHeader);
    }

    Cache<String, Object> stringObjectCache = CacheUtils.builder(120);

    public ZhongConfig getLocalConfig() {
        return getConfig(0);
    }



    public ZhongConfig getConfig(Integer mode) {
        //1xiao 2daxiang 3jinshe

        ZhongConfig zhongConfig = hashMap.get(mode);
        if (zhongConfig == null) {
            configMap();
        }
        zhongConfig = hashMap.get(mode);
        //AperExceptionUtils.throwAperException(zhongConfig==null,"zhong config is null,mode="+mode);
        String key = "initConfig";
        if (stringObjectCache.getIfPresent(key) == null) {
            //10min刷新缓存
            ThreadPoolUtils.submitTask(() -> {
                if(stringObjectCache.getIfPresent(key)==null){
                    stringObjectCache.put(key, "1");
                    configMap();
                }


            });
        }
        return zhongConfig;
    }

    public Map<String, String> commonHeader;//请求其他助手的header

    public synchronized void configMap() {

        String key = "system:config:all";
        String filename = configFilename;
        String body = redisHelper.loadByCache(key, String.class);
        if(StrUtils.isBlank(body)){
            InputStream inputStream = null;
            try  {
                //   // 通过类加载器获取资源的输入流

                //File configFile = new File(filename);
                inputStream = new FileInputStream(filename);
                body = IoUtil.read(inputStream, StandardCharsets.UTF_8);
                body = JSONUtil.formatJsonStr(body);
                redisHelper.save(key,body,7, TimeUnit.DAYS);
            } catch (Exception e) {
                log.error("获取配置出错", e);
            }finally {
                CloseUtils.close(inputStream);
            }
        }else{
            try{
                body = JSONUtil.formatJsonStr(body);
                FileUtil.writeString(body,filename, Charset.defaultCharset());
            }catch (Exception e){
                log.error("更新本地配置文件失败,filename：{}",filename, e);
            }
        }
        jsonObject = JSONObject.parseObject(body);
        fiddleHeader = JacksonUtils.toMap(jsonObject.getString("fiddleHeader"),String.class,String.class);
        String headerMapJSON = jsonObject.getJSONObject("common").getString("headerMap");
        commonHeader = JacksonUtils.toMap(headerMapJSON, String.class, String.class);
        fillConfig(0);//本地配置

        //fillConfig(1);
        //大象
        fillConfig(2);
        //金蛇
        fillConfig(3);
    }

    public void fillConfig(Integer key) {
        ZhongConfig zhongConfig = jsonObject.getJSONObject(key.toString()).toJavaObject(ZhongConfig.class);
        Map<String, String> commonHeaderMap = new HashMap<>(commonHeader);
        Map<String, String> configHeaderMap = zhongConfig.getHeaderMap();
        if (CollUtil.isNotEmpty(configHeaderMap)) {
            commonHeaderMap.putAll(configHeaderMap);
        }
        zhongConfig.setHeaderMap(commonHeaderMap);
        zhongConfig.setAesIvBytes(zhongConfig.getAesIvStr().getBytes());
        zhongConfig.setAesKeyBytes(zhongConfig.getAesKeyStr().getBytes());
        zhongConfig.setDomains(zhongConfig.getDomains());
        this.hashMap.put(key, zhongConfig);
    }


   /* public boolean getProxyEnable(){
        Boolean enable = getLocalConfig().getEnableProxy();
        if(Objects.equals(enable,true)){
            return true;
        }
        return false;
    }

    public HttpHost getProxy(){
        if(getProxyEnable()){
            return ProxyUtils.getProxy();
        }
        return null;


    }*/
}
